<template>
  <div class="work-records-container">
    <div class="header">
      <div class="left">
        <h2>工作记录管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加记录
        </el-button>
      </div>
      <div class="right">
        <el-select
          v-model="statusFilter"
          placeholder="审核状态"
          clearable
          @change="handleStatusChange"
          class="status-filter"
        >
          <el-option label="待审核" value="PENDING" />
          <el-option label="已通过" value="APPROVED" />
          <el-option label="已拒绝" value="REJECTED" />
        </el-select>
        <el-input
          v-model="searchQuery"
          placeholder="搜索学生姓名"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="records"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="employee.student.name" label="学生姓名" width="120" />
        <el-table-column prop="employee.position.title" label="岗位名称" min-width="150" />
        <el-table-column prop="workDate" label="工作日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.workDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column label="工作时间" width="200">
          <template #default="{ row }">
            {{ row.startTime }} - {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="workHours" label="工作时长" width="100">
          <template #default="{ row }">
            {{ row.workHours }}小时
          </template>
        </el-table-column>
        <el-table-column prop="workContent" label="工作内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                v-if="row.status === 'PENDING'"
                type="success"
                size="small"
                @click="handleReview(row)"
              >
                审核
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleView(row)"
              >
                查看
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loading && (!records || records.length === 0)" class="empty-data">
        <el-empty description="暂无数据" />
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="在岗人员" prop="employeeId">
          <el-select 
            v-model="form.employeeId"
            placeholder="请选择在岗人员"
            filterable
          >
            <el-option
              v-for="employee in employees"
              :key="employee.id"
              :label="`${employee.student.name} - ${employee.position.title}`"
              :value="employee.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作日期" prop="workDate">
          <el-date-picker
            v-model="form.workDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="选择时间"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="选择时间"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="工作内容" prop="workContent">
          <el-input
            v-model="form.workContent"
            type="textarea"
            :rows="4"
            placeholder="请输入工作内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="工作记录详情"
      v-model="viewDialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="学生姓名">
          {{ selectedRecord?.employee.student.name }}
        </el-descriptions-item>
        <el-descriptions-item label="岗位名称">
          {{ selectedRecord?.employee.position.title }}
        </el-descriptions-item>
        <el-descriptions-item label="工作日期">
          {{ formatDate(selectedRecord?.workDate, 'YYYY-MM-DD') }}
        </el-descriptions-item>
        <el-descriptions-item label="工作时间">
          {{ selectedRecord?.startTime }} - {{ selectedRecord?.endTime }}
        </el-descriptions-item>
        <el-descriptions-item label="工作时长">
          {{ selectedRecord?.workHours }}小时
        </el-descriptions-item>
        <el-descriptions-item label="工作内容">
          {{ selectedRecord?.workContent }}
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(selectedRecord?.status)">
            {{ getStatusText(selectedRecord?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核意见" v-if="selectedRecord?.reviewComments">
          {{ selectedRecord.reviewComments }}
        </el-descriptions-item>
        <el-descriptions-item label="审核人" v-if="selectedRecord?.reviewer">
          {{ selectedRecord.reviewer.name }}
        </el-descriptions-item>
        <el-descriptions-item label="审核时间" v-if="selectedRecord?.reviewTime">
          {{ formatDate(selectedRecord.reviewTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      title="审核工作记录"
      v-model="reviewDialogVisible"
      width="500px"
    >
      <el-form
        ref="reviewFormRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="reviewForm.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="reviewComments">
          <el-input
            v-model="reviewForm.reviewComments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="reviewing"
          @click="submitReview"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWorkRecords, createWorkRecord, reviewWorkRecord, deleteWorkRecord } from '@/api/admin/workRecord'
import { getEmployees } from '@/api/admin/employee'
import { formatDate } from '@/utils/format'

// 表格数据
const loading = ref(false)
const records = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const statusFilter = ref('')

// 表单数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitting = ref(false)
const employees = ref([])

const form = ref({
  employeeId: null,
  workDate: null,
  startTime: null,
  endTime: null,
  workContent: ''
})

// 表单验证规则
const rules = {
  employeeId: [
    { required: true, message: '请选择在岗人员', trigger: 'change' }
  ],
  workDate: [
    { required: true, message: '请选择工作日期', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  workContent: [
    { required: true, message: '请输入工作内容', trigger: 'blur' }
  ]
}

// 获取工作记录列表
const fetchRecords = async () => {
  try {
    loading.value = true
    const response = await getWorkRecords({
      page: currentPage.value - 1,
      size: pageSize.value,
      status: statusFilter.value,
      search: searchQuery.value
    })
    
    if (response) {
      records.value = response.content
      total.value = response.totalElements
    }
  } catch (error) {
    console.error('Failed to fetch records:', error)
    ElMessage.error('获取工作记录失败')
  } finally {
    loading.value = false
  }
}

// 获取在岗人员列表
const fetchEmployees = async () => {
  try {
    const response = await getEmployees({
      page: 0,
      size: 1000
    })
    if (response) {
      employees.value = response.content
    }
  } catch (error) {
    console.error('Failed to fetch employees:', error)
    ElMessage.error('获取在岗人员列表失败')
  }
}

// 处理状态筛选
const handleStatusChange = () => {
  currentPage.value = 1
  fetchRecords()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRecords()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRecords()
}

// 添加记录
const handleAdd = () => {
  dialogTitle.value = '添加工作记录'
  form.value = {
    employeeId: null,
    workDate: null,
    startTime: null,
    endTime: null,
    workContent: ''
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 直接使用日期选择器和时间选择器返回的值
    const formattedData = {
      employeeId: form.value.employeeId,
      workDate: form.value.workDate,  // 日期选择器已经返回 YYYY-MM-DD 格式
      startTime: form.value.startTime, // 时间选择器已经返回 HH:mm 格式
      endTime: form.value.endTime,     // 时间选择器已经返回 HH:mm 格式
      workContent: form.value.workContent
    }
    
    await createWorkRecord(formattedData)
    ElMessage.success('添加成功')
    dialogVisible.value = false
    fetchRecords()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('提交失败: ' + (error.response?.data || error.message))
  } finally {
    submitting.value = false
  }
}

// 查看详情
const viewDialogVisible = ref(false)
const selectedRecord = ref(null)

const handleView = (row) => {
  selectedRecord.value = row
  viewDialogVisible.value = true
}

// 审核相关
const reviewDialogVisible = ref(false)
const reviewFormRef = ref(null)
const reviewing = ref(false)

const reviewForm = ref({
  approved: true,
  reviewComments: ''
})

const reviewRules = {
  reviewComments: [
    { required: true, message: '请输入审核意见', trigger: 'blur' }
  ]
}

const handleReview = (row) => {
  selectedRecord.value = row
  reviewForm.value = {
    approved: true,
    reviewComments: ''
  }
  reviewDialogVisible.value = true
}

const submitReview = async () => {
  if (!reviewFormRef.value) return
  
  try {
    await reviewFormRef.value.validate()
    reviewing.value = true
    
    await reviewWorkRecord(selectedRecord.value.id, reviewForm.value)
    ElMessage.success('审核成功')
    reviewDialogVisible.value = false
    fetchRecords()
  } catch (error) {
    console.error('Review submission failed:', error)
    ElMessage.error('审核失败')
  } finally {
    reviewing.value = false
  }
}

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该工作记录吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteWorkRecord(row.id)
      ElMessage.success('删除成功')
      fetchRecords()
    } catch (error) {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'PENDING':
      return 'warning'
    case 'APPROVED':
      return 'success'
    case 'REJECTED':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'PENDING':
      return '待审核'
    case 'APPROVED':
      return '已通过'
    case 'REJECTED':
      return '已拒绝'
    default:
      return '未知'
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchEmployees()
  fetchRecords()
})
</script>

<style scoped>
.work-records-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.right {
  display: flex;
  gap: 16px;
}

.status-filter {
  width: 120px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style> 